<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>websocket使用</title>
  </head>
  <body>
    Welcome
    <br />
    <input id="text" value="这是一条测试消息" />
    <button onclick="sendMessage()">发送消息</button>
    <hr />
    <button onclick="openSocket()">连接socket</button>
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr />
    <div id="message"></div>
  </body>
  <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
  <script>
    var socket;
    function openSocket() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        //指定要连接的服务器地址与端口
        var socketUrl = "ws://localhost:8081/api/websocket/localId";
        console.log(socketUrl);
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 实例化WebSocket对象，建立连接
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
          setMessageInnerHTML("websocket已打开");
        };
        //获得消息事件
        socket.onmessage = function (msg) {
          console.log(msg.data);
          //消息进入后的处理逻辑
          setMessageInnerHTML("服务端回应: " + msg.data);
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
          setMessageInnerHTML("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    }

    function sendMessage() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");

        var message = $("#text").val();
        socket.send(message);

        setMessageInnerHTML(message);
      }
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
      $("#message").append(innerHTML + "<br/>");
    }

    //关闭WebSocket连接
    function closeWebSocket() {
      socket.close();
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
      closeWebSocket();
    };
  </script>
</html>
